import {Coverage, TestParser} from '../../test-parser'
import {readFile,checkCoverageFileExist} from '../../utils'
import * as cheerio from 'cheerio'
import * as step from '@flow-step/step-toolkit'

export class PhpUnitTestParser implements TestParser {
    async coverageFile(path: string): Promise<string> {
        if (!path.endsWith('.html')) {
            throw new Error(`Input variable 'reportPath' should reference a report with html extension`)
        }

        await checkCoverageFileExist(path)
        return path
    }

    htmlFile(path: string): string {
        return path
    }

    async parse(path: string): Promise<Coverage> {
        step.info(`Parsing Php-UnitTest Html report: ${path}`)
        const htmlContent = await readFile(path)
        step.debug(`htmlContent: ${htmlContent}`)
        return this.count(htmlContent)
    }

    async count(htmlContent: string): Promise<Coverage>{
        const $ = cheerio.load(htmlContent)
        let res = {
            total : 0,
            passed : 0,
            failed : 0,
            skipped : 0,
            passedRate : 0
        } as Coverage

        res.total = this.getBySelector($, 'li')
        res.passed = this.getBySelector($, 'li.success, li[style="color: #555753;"]')
        res.failed = this.getBySelector($, 'li.defect, li[style="color: #ef2929;"]')
        res.skipped = res.total - res.passed - res.failed

        if (res.total != 0){
            res.passedRate = 100 - (res.failed * 100 / res.total)
        }
        return res
    }

    getBySelector($: cheerio.Root, selector: string): number {
        const val = $(selector).length

        if (isNaN(val)) {
            throw new Error('Error converting text to integer');
        }
        return val;
    }
}
